package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.SaleStatusContentRecyclerViewAdapter;
import com.weixin.paleituo.adapter.SaleStatusMenuRecyclerViewAdapter;
import com.weixin.paleituo.base.BaseActivity;
import com.weixin.paleituo.bean.BuildingsBean;
import com.weixin.paleituo.bean.HouseSaleStateBean;
import com.weixin.paleituo.bean.LevelsBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.UnitsBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.CheckSaleStatueCityEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.AlertPopuCommon;
import com.weixin.paleituo.view.LoadingPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 售卖情况
 */
public class SaleStatusActivity extends BaseActivity {


    @BindView(R.id.recycle_nume_activity_sale_status)
     RecyclerView mRecyclerViewmenu;
    @BindView(R.id.recycle_content_activity_sale_status)
    RecyclerView    mRecyclerVieContent;
    @BindView(R.id.ll_headroots_layout_head)
     LinearLayout mHeadRoot;
    @BindView(R.id.ll_arrowroot_layout_head)
     LinearLayout mLlarrowRoot;
    @BindView(R.id.iv_back_layout_head)
     ImageView mIvBack;
    @BindView(R.id.tv_title_layout_head)
    TextView mTvTitle;
    @BindView(R.id.iv_arrow_layout_head)
    ImageView mImArrow;

    @BindView(R.id.tv_small_title_layout_head)
    TextView mTvSmallTitle;
    private SaleStatusMenuRecyclerViewAdapter mSaleStatusMenuRecyclerViewAdapter;
    private SaleStatusContentRecyclerViewAdapter mSaleStatusContentRecyclerViewAdapter;
    private List<String> mList;
    private LoadingPager mLoadingPager;
    private Map<String, String> mMap;
    private Dialog mLoadingDialog;
    private List<UnitsBean> mUnits=new ArrayList();
    private List<LevelsBean> mLevels=new ArrayList<>();
    private AlertPopuCommon mPopuCommon;


    @Override
    protected void initView() {

        mLoadingPager = new LoadingPager(this,Contans.HOUSE_SOLDOUT_TYPE) {
            @Override
            protected void close() {
                finish();
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(SaleStatusActivity.this,R.layout.activity_sale_status);
            }

            @Override
            protected void reLoading() {
                retryLoading();



            }
        };


      setContentView(mLoadingPager);
    }

    @Override
    protected void initData() {
        super.initData();
        mList=new ArrayList();
        mMap = new HashMap<>();
        EventBus.getDefault().register(this);


        mSaleStatusMenuRecyclerViewAdapter = new SaleStatusMenuRecyclerViewAdapter(this,mUnits);
        //设置布局管理器
        mRecyclerViewmenu.setLayoutManager(new LinearLayoutManager(this));
        //设置adapter
        mRecyclerViewmenu.setAdapter(mSaleStatusMenuRecyclerViewAdapter);
        //设置Item增加、移除动画
        mRecyclerViewmenu.setItemAnimator(new DefaultItemAnimator());



        mSaleStatusContentRecyclerViewAdapter = new SaleStatusContentRecyclerViewAdapter(this,mLevels);
        //设置布局管理器
        mRecyclerVieContent.setLayoutManager(new LinearLayoutManager(this));
        //设置adapter
        mRecyclerVieContent.setAdapter(mSaleStatusContentRecyclerViewAdapter);
        //设置Item增加、移除动画
        mRecyclerVieContent.setItemAnimator(new DefaultItemAnimator());





        retryLoading();


        //


    }

    /**
     * 重加载
     */
    private void retryLoading() {
        String houseid = getIntent().getStringExtra(Contans.INTENT_DATA);
        Observable<StatusCode<HouseSaleStateBean>> houseSaleState = ApiUtils.getApi().getHouseSaleState(houseid);

        HttpUtil.getInstance().toSubscribe(houseSaleState, new ProgressSubscriber<HouseSaleStateBean>(this) {
            @Override
            protected void _onNext(StatusCode<HouseSaleStateBean> t) {
                HouseSaleStateBean houseSaleStateBean = t.getData();
                List<BuildingsBean> buildings = houseSaleStateBean.getBuildings();
                List<UnitsBean> units = houseSaleStateBean.getUnits();
                if (t.isFlag()&&houseSaleStateBean!=null&&buildings!=null &&buildings.size()>0 &&units!=null &&units.size()>0){
                    mLoadingPager.showPagerView(Contans.STATE_SUCCEED);
                    setData(houseSaleStateBean);
                }else {
                    mLoadingPager.showPagerView(Contans.STATE_EMPTY);
                }

            }

            @Override
            protected void _onError(String message) {

                mLoadingPager.showPagerView(Contans.STATE_ERROR);

            }
        },"",lifecycleSubject,false,true);
    }

    /**
     * 设置数据
     * @param houseSaleStateBean
     */
    private void setData(final HouseSaleStateBean houseSaleStateBean) {

        mTvSmallTitle.setVisibility(View.VISIBLE);



        mTvSmallTitle.setText(houseSaleStateBean.getBuildings().get(0).getBuilding()+"");
        mImArrow.setVisibility(View.VISIBLE);
        mTvTitle.setVisibility(View.VISIBLE);
        mTvTitle.setText(houseSaleStateBean.getHouses()+"");
        mUnits.clear();
        List<UnitsBean> units = houseSaleStateBean.getUnits();
        if (units!=null){
            mUnits.addAll(units);
            mSaleStatusMenuRecyclerViewAdapter.notifyDataSetChanged();
           /* mSaleStatusMenuRecyclerViewAdapter = new SaleStatusMenuRecyclerViewAdapter(this,mUnits);
            //设置布局管理器
            mRecyclerViewmenu.setLayoutManager(new LinearLayoutManager(this));
            //设置adapter
            mRecyclerViewmenu.setAdapter(mSaleStatusMenuRecyclerViewAdapter);
            //设置Item增加、移除动画
            mRecyclerViewmenu.setItemAnimator(new DefaultItemAnimator());*/
            //添加分割线

            List<LevelsBean> levels = houseSaleStateBean.getUnits().get(0).getLevels();
            if (levels!=null){
                mLevels.clear();
                mLevels .addAll(levels);
                mSaleStatusContentRecyclerViewAdapter.notifyDataSetChanged();
               /* mSaleStatusContentRecyclerViewAdapter = new SaleStatusContentRecyclerViewAdapter(this,mLevels);
                //设置布局管理器
                mRecyclerVieContent.setLayoutManager(new LinearLayoutManager(this));
                //设置adapter
                mRecyclerVieContent.setAdapter(mSaleStatusContentRecyclerViewAdapter);
                //设置Item增加、移除动画
                mRecyclerVieContent.setItemAnimator(new DefaultItemAnimator());*/
                //添加分割线
       /* mRecyclerVieContent.addItemDecoration(new DividerItemDecoration(
                this, DividerItemDecoration.VERTICAL));*/

            }


            mSaleStatusMenuRecyclerViewAdapter.setOnItemClickListener(new SaleStatusMenuRecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void onClick(View v, int position) {
                    mLevels.clear();

                    if (mUnits.get(position)!=null && mUnits.get(position).getLevels()!=null){
                        mLevels.addAll(mUnits.get(position).getLevels());
                        mRecyclerVieContent.smoothScrollToPosition(0);
                        mSaleStatusContentRecyclerViewAdapter.notifyDataSetChanged();
                    }
                    mSaleStatusMenuRecyclerViewAdapter.setCheckPostion(position);
                    mSaleStatusMenuRecyclerViewAdapter.notifyDataSetChanged();
                }
            });



        }



//得到栋
        List<BuildingsBean> buildings = houseSaleStateBean.getBuildings();

      mList.clear();
        if (buildings!=null && buildings.size()>0){
            for (BuildingsBean building :buildings){
                String building1 = building.getBuilding();

                mList.add(building1);

                mMap.put(building1,building.getBuildingId()+"");

            }


        }


    }

    @Override
    protected void initEvent() {
        super.initEvent();

        mLlarrowRoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopuCommon==null){

                    mPopuCommon = new AlertPopuCommon(SaleStatusActivity.this, Contans.DIAG_TYPE_HOUSE_SALE_STATUE, mList,mTvSmallTitle.getText().toString());
                    mPopuCommon.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            mImArrow.setImageResource(R.mipmap.sj_h);

                        }
                    });
                }else {

                    mPopuCommon.setChekStr(mTvSmallTitle.getText().toString());
                }
                mImArrow.setImageResource(R.mipmap.price_up);
                mPopuCommon.showAsDropDown(mHeadRoot);

            }
        });

        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
    public static void startActivity(Context context,String houseid){
        Intent intent=new Intent(context,SaleStatusActivity.class);
        intent.putExtra(Contans.INTENT_DATA,houseid);
        context.startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void checkBuilding(CheckSaleStatueCityEvent checkSaleStatueCityEvent){
        String mbuildingName = checkSaleStatueCityEvent.getMbuilding();

        String buildingId = mMap.get(mbuildingName);

            //请求数据
        if (StringUtils.isEmpty(buildingId) ||mbuildingName.equals(mTvSmallTitle.getText().toString())){
            return;
        }
        mTvSmallTitle.setText(checkSaleStatueCityEvent.getMbuilding());
        Observable observable = ApiUtils.getApi().getHouseUnit(buildingId).compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                if (mLoadingDialog == null) {

                    mLoadingDialog = LoadingDialogUtils.createLoadingDialog(SaleStatusActivity.this, "");
                }
                LoadingDialogUtils.show(mLoadingDialog);

            }
        }).subscribeOn(AndroidSchedulers.mainThread());

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<UnitsBean>>(this) {

            @Override
            protected void _onNext(StatusCode<List<UnitsBean>> t) {
                List<UnitsBean> uiUtils = t.getData();
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                if (uiUtils!=null &&uiUtils.size()>0){
                    mSaleStatusMenuRecyclerViewAdapter.setCheckPostion(0);
                    //   mSaleStatusMenuRecyclerViewAdapter.setList(uiUtils);
                    mUnits.clear();
                    mUnits.addAll(uiUtils);
                    mSaleStatusMenuRecyclerViewAdapter.notifyDataSetChanged();


                    //  mSaleStatusContentRecyclerViewAdapter.setLevels(uiUtils.get(0).getLevels());
                    mLevels.clear();
                    mLevels.addAll(uiUtils.get(0).getLevels());
                    mSaleStatusContentRecyclerViewAdapter.notifyDataSetChanged();
                }else {
                    mLevels.clear();
                    mUnits.clear();
                    ToastUtils.makeText(t.getDetailMsg()+"");
                    mSaleStatusContentRecyclerViewAdapter.notifyDataSetChanged();
                    mSaleStatusMenuRecyclerViewAdapter.notifyDataSetChanged();
                }
            }

            @Override
            protected void _onError(String message) {

              //  mSaleStatusMenuRecyclerViewAdapter.setList();
               // mSaleStatusMenuRecyclerViewAdapter.notifyDataSetChanged();

              //  mSaleStatusContentRecyclerViewAdapter.setLevels(uiUtils.get(0).getLevels());
              //  mSaleStatusContentRecyclerViewAdapter.notifyDataSetChanged();
                  mLevels.clear();
                 mUnits.clear();
                ToastUtils.makeText(message);
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                mSaleStatusContentRecyclerViewAdapter.notifyDataSetChanged();
                mSaleStatusMenuRecyclerViewAdapter.notifyDataSetChanged();

            }
        },"",lifecycleSubject,false,true);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }
}
